package com.lagou.zk;

import com.lagou.db.DBCPUtils;
import org.I0Itec.zkclient.ZkClient;
import org.junit.Test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;

public class DbConfZK {

    //初始化数据库连接池的配置参数
    public static void main(String[] args) throws SQLException {
        DbConfZK.init();
//        DbConfZK.getDbConf();
//        Connection connection = DBCPUtils.getConnection();
//
//        Statement statement = connection.createStatement();
//
//        String sql = "show tables";
//
//        ResultSet resultSet = statement.executeQuery(sql);
//        while (resultSet.next()) {
//            String tableName = resultSet.getString(1);
//            System.out.println(tableName);
//        }
//
//        System.out.println(resultSet);
//
//        DBCPUtils.close(connection, statement, resultSet);
    }


    public static HashMap<String, String> dbConf = new HashMap<>();

    public static void init() {

        ZkClient client = new ZkClient("node01:2181");
        client.setZkSerializer(new ZkStrSerializer());
        client.deleteRecursive("/dbcp");

        if (!client.exists("/dbcp")) {
            String configData = "com.mysql.cj.jdbc.Driver|";
            configData += "jdbc:mysql://39.97.122.140:7983/pipeline?characterEncoding=UTF-8|";
            configData += "phpOnAvcp|";
            configData += "n6Rs%^2M!vx90)d";

            client.createPersistent("/dbcp", configData);
        }

    }

    public static HashMap<String, String> getDbConf() {


        ZkClient client = new ZkClient("node01:2181");

        client.setZkSerializer(new ZkStrSerializer());

        String confData = client.readData("/dbcp");


        String[] data = confData.split("\\|");

        dbConf.clear();
        dbConf.put("driver_name", data[0]);
        dbConf.put("url", data[1]);
        dbConf.put("username", data[2]);
        dbConf.put("password", data[3]);

        return dbConf;
    }
}
